<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8"/>
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
		<meta name="HandheldFriendly" content="true"/>
		<meta name="MobileOptimized" content="320"/>
		<title>拍图识字</title>
		<script type="text/javascript" src="js/common.js"></script>
		<script type="text/javascript" src="js/mui.min.js" ></script>
		<script type="text/javascript">
			var i=1,gentry=null,w=null;
			var hl=null,le=null,de=null,ie=null;
			var unv=true;
			var bUpdated=false; //用于兼容可能提前注入导致DOM未解析完更新的问题
			// H5 plus事件处理
			function plusReady(){
				// 获取摄像头目录对象
				plus.io.resolveLocalFileSystemURL('_doc/', function(entry){
					entry.getDirectory('camera', {create:true}, function(dir){
						gentry = dir;
			//			updateHistory();
					}, function(e){
						mui.toast('Get directory "camera" failed: '+e.message);
					} );
				}, function(e){
					mui.toast('Resolve "_doc/" failed: '+e.message);
				});
			}
			if(window.plus){
				plusReady();
			}else{
				document.addEventListener('plusready', plusReady, false);
			}
			// 监听DOMContentLoaded事件
			document.addEventListener('DOMContentLoaded', function(){
				// 获取DOM元素对象
				hl=document.getElementById('history');
				le=document.getElementById('empty');
				de=document.getElementById('display');
				if(ie=document.getElementById('index')){
					ie.onchange=indexChanged;
				}
				// 判断是否支持video标签
				unv=!document.createElement('video').canPlayType;
			//	updateHistory();
			},false );
			function changeIndex(){
				mui.toast('选择摄像头：');
				ie.focus();
			}
			function indexChanged(){
				de.innerText = ie.options[ie.selectedIndex].innerText;
				i = parseInt(ie.value);
				mui.toast(de.innerText);
			}
			
			              
			// 拍照
			function getImage(){
			//	mui.toast('开始拍照：');
				cleanHistory();
				var cmr = plus.camera.getCamera();
				cmr.captureImage(function(p){
					mui.toast('成功：'+p);
					plus.io.resolveLocalFileSystemURL(p, function(entry){
						getBase64(entry.fullPath);
						createItem(entry);
					}, function(e){
						mui.toast('读取拍照文件错误：'+e.message);
					});
				}, function(e){
					mui.toast('失败：'+e.message);
				}, {filename:'_doc/camera/',index:1});
			}
			// 录像
			function getVideo(){
				mui.toast('开始录像：');
				var cmr = plus.camera.getCamera();
				cmr.startVideoCapture(function(p){
					mui.toast('成功：'+p);
					plus.io.resolveLocalFileSystemURL(p, function(entry){
						createItem(entry);
					}, function(e){
						mui.toast('读取录像文件错误：'+e.message);
					} );
				}, function(e){
					mui.toast('失败：'+e.message);
				}, {filename:'_doc/camera/',index:i});
			}
			// 显示文件
			function displayFile(li){
				if(w){
					mui.toast('重复点击！');
					return;
				}
				if(!li || !li.entry){
					ouSet('无效的媒体文件');
					return;
				}
				var name = li.entry.name;
				var suffix = name.substr(name.lastIndexOf('.'));
				var url = '';
				if(suffix=='.mov' || suffix=='.3gp' || suffix=='.mp4' || suffix=='.avi'){
					//if(unv){plus.runtime.openFile('_doc/camera/'+name);return;}
					url = '/plus/camera_video.html';
				} else {
					url = '/plus/camera_image.html';
				}
				w=plus.webview.create(url,url,{hardwareAccelerated:true,scrollIndicator:'none',scalable:true,bounce:'all'});
				w.addEventListener('loaded', function(){
					w.evalJS('loadMedia("'+li.entry.toLocalURL()+'")');
					//w.evalJS('loadMedia("'+'http://localhost:13131/_doc/camera/'+name+'")');
				}, false );
				w.addEventListener('close', function(){
					w = null;
				}, false);
				w.show('pop-in');
			}
			
			// 添加播放项
			function createItem(entry){
				var li = document.createElement('li');
				li.className = 'ditem';
				li.innerHTML = '<span class="iplay"><font class="aname"></font><br/><font class="ainf"></font></span>';
				li.setAttribute('onclick', 'displayFile(this)' );
				hl.insertBefore( li, le.nextSibling );
				li.querySelector('.aname').innerText = entry.name;
				li.querySelector('.ainf').innerText = '...';
				li.entry = entry;
				updateInformation(li);
				// 设置空项不可见
				le.style.display = 'none';
			}
			// 获取相册文件信息
			function updateInformation(li){
				if(!li || !li.entry){
					return;
				}
				var entry = li.entry;
				entry.getMetadata(function(metadata){
					li.querySelector('.ainf').innerText = dateToStr(metadata.modificationTime);
				}, function(e){
					mui.toast('获取文件"'+entry.name+'"信息失败：'+e.message);
				} );
			}
			// 获取相册历史列表
			function updateHistory(){
				if(bUpdated||!gentry||!document.body){//兼容可能提前注入导致DOM未解析完更新的问题
					return;
				}
			  	var reader = gentry.createReader();
			  	reader.readEntries(function(entries){
			  		for(var i in entries){
			  			if(entries[i].isFile){
			  				createItem(entries[i]);
			  			}
			  		}
			  	}, function(e){
			  		mui.toast('读取相册列表失败：'+e.message);
			  	});
			  	bUpdated = true;
			}
			// 清除历史记录
			function cleanHistory(){
				hl.innerHTML = '<li id="empty" class="ditem-empty">无历史记录</li>';
				le = document.getElementById('empty');
				// 删除相册文件
			//	mui.toast('清空拍照录像历史记录：');
				gentry.removeRecursively(function(){
					// Success
			//		mui.toast('成功！');
				}, function(e){
					mui.toast('失败：'+e.message);
				});
			}
					</script>
					<link rel="stylesheet" href="css/common.css" type="text/css" charset="utf-8"/>
					<style type="text/css">
			.aname {
				font-size: 16px;
			}
			.ainf {
				font-size: 12px;
			}
			.iplay {
				display: block;
				background: no-repeat right center url();
				background-size: 50px 44px;
				-ms-touch-action: auto;
			}
			.bottom_footer {  
			       position: fixed; /*or前面的是absolute就可以用*/  
			       bottom: 10px;
			       width: 100%;
			}
			header{
				background-color: deepskyblue;
			}
		</style>
	</head>
	<body>
		<header id="header" style="background-color: deepskyblue;">
			<div class="nvbt iback" onclick="back()"></div>
			<div class="nvtt" style="color: #fff;">拍图识字</div>
			<!--<div class="nvbt idoc" onclick="openDoc('Camera Document','/doc/camera.html')"></div>-->
		</header>
		<div id="dcontent" class="dcontent" style="height: 300px;">
			<!--<div class="button" onclick="changeIndex();">
				选择：<span id="display" style="color:#FF0000">主摄像头</span>
				<div style="width:0px;height:0px;overflow:hidden;"><select id="index">
					<option value='1' selected="true">主摄像头</option>
					<option value='2' >辅摄像头</option>
				</select></div>
			</div>-->
			<!--<div class="button" onclick="getVideo()">录像</div>-->
			<br/>
			<!-- History list -->
			<ul id="history" class="dlist" style="text-align:left;">
				<li id="empty" class="ditem-empty">暂无识别，请拍照</li>
			</ul>
			<div align="left"><span style="padding-left: 20px;">识别文字：</span>
				<span id="scanText" style="color: red;padding: 20px;"></span></div>
			<br/>
			<!--<div class="button button-waring" onclick="cleanHistory()">清空历史记录</div>-->
			<!--<div class="button button-waring" onclick="sp()">暂停</div>-->
			<br/>
		</div>
		<div class="bottom_footer" align="center">
			<button style="background-color: deepskyblue;width: 40%;height: 70px ;position: relative;" onclick="getImage()"><img src="images/xiangji.png" width="60px"/></button>
			<button style="background-color: deepskyblue;width: 40%;height: 70px ;position: relative;" onclick="repetition()"><img src="images/chongfu.png" width="60px"/></button>
		</div>
		<!--播放声音-->
		<audio src="" id="playMp3"></audio>
		<!--<div id="output">
Camera管理摄像头设备，可用于拍摄照片、录制视频文件。
		</div>-->
	</body>
	<script type="text/javascript" src="js/immersed.js" ></script>
	<script>
		document.getElementById("header").style="background-color: deepskyblue;padding-top:25px"
		function getBase64 (path) {
		    var img = new Image();
		    img.src = path; // 传过来的图片路径在这里用。
		    img.onload = function() {
		        var that = this;
//		        console.log("wh = " + that.width + "," + that.height);
		        //生成比例 
		        var w = that.width,
		            h = that.height,
		            scale = w / h;
		        w = 480 || w; //480  你想压缩到多大，改这里
		        h = w / scale;
		        //生成canvas
		        var canvas = document.createElement('canvas');
		
		        var ctx = canvas.getContext('2d');
		
		        canvas.width = w;
		        canvas.height = h;
		
		        ctx.drawImage(that, 0, 0, w, h);
		
		        var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8); //1最清晰，越低越模糊。
		        base64 = base64.toString().replace('data:image/jpg;base64,','');
		        base64 = base64.toString().replace('data:image/jpeg;base64,','');
		        getAccessToken(base64);
			}
		}
		var accessToken = '';
		
		function getAccessToken (base64) {
			var myDate = new Date();
			var nowTime = myDate.getTime();
			var cacheTime = localStorage.getItem("time");
			accessToken = localStorage.getItem("accessToken");
			var panduan = (nowTime-2592000000) > cacheTime ;
			if(panduan || accessToken == '' || accessToken == undefined || accessToken == 'undefined'){
				mui.ajax('https://aip.baidubce.com/oauth/2.0/token',{
					data:{
						grant_type:'client_credentials',
						client_id:'jNDCvwRmy7AXXuMC2Dri539F',
						client_secret:'luljmdOgVF7IF3g2hjAl6lzCayL1A1W0'
					},
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					success:function(data){
						accessToken = data.access_token;
						localStorage.setItem("accessToken",accessToken);
						localStorage.setItem("time",nowTime);
		        		getImgText(accessToken,base64);
					},
					error:function(xhr,type,errorThrown){
						alert("TokenError");
					}
				});
			}else{
		        getImgText(accessToken,base64);
			}
			
		}
		
		function getImgText (accessToken,base64Data) {
			var imgtext = '';
			mui.ajax('https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic',{
				data:{
					access_token:accessToken,
					image:base64Data
				},
				dataType:'json',//服务器返回json格式数据
				type:'post',//HTTP请求类型
				timeout:10000,//超时时间设置为10秒；
				success:function(data){
					var words_result = data.words_result;
					mui.each(words_result,function (index,element) {
						imgtext +=element.words;
					})
					document.getElementById("scanText").innerHTML=imgtext;
		        	var mp3Url = "http://tsn.baidu.com/text2audio?tok="+accessToken+"&tex="+encodeURI(imgtext)+"&cuid=cuijiajun&ctp=1&lan=zh";
		        	document.getElementById("playMp3").src=mp3Url;
		        	document.getElementById("playMp3").play();
				},
				error:function(xhr,type,errorThrown){
					var t = "识别失败，请重试";
					document.getElementById("scanText").innerHTML=t;
		        	var mp3Url = "http://tsn.baidu.com/text2audio?tok="+accessToken+"&tex="+encodeURI(t)+"&cuid=cuijiajun&ctp=1&lan=zh";
		        	document.getElementById("playMp3").src=mp3Url;
		        	document.getElementById("playMp3").play();
					mui.toast("voiceError");
				}
			});
		}
		function repetition() {
		    document.getElementById("playMp3").play();
		}
		
	</script>
</html>